import os
import sys

# 添加项目根目录到 Python 路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QLineEdit, QHBoxLayout
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QFont, QPixmap
from qfluentwidgets import SmoothScrollArea, PrimaryPushButton, InfoBar, InfoBarPosition
from modules import MatrixModule, PointsModule, CombinerModule
from interfaces.matrix_editor_dialog import MatrixEditorDialog
from interfaces.points_editor_dialog import PointsEditorDialog


class HoverMoveButton(PrimaryPushButton):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.original_pos = self.pos()
        self.move_offset = QPoint(5, 5)  # 向右下角移动的偏移量

    def enterEvent(self, event):
        self.original_pos = self.pos()
        self.move(self.pos() + self.move_offset)
        super().enterEvent(event)

    def leaveEvent(self, event):
        self.move(self.original_pos)
        super().leaveEvent(event)


class DataGeneratorInterface(SmoothScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.view = QWidget(self)
        self.vBoxLayout = QVBoxLayout(self.view)
        self.setWidget(self.view)
        self.setWidgetResizable(True)

        # 将背景样式直接应用到主视图，修改背景图片路径指向pic文件夹
        self.view.setStyleSheet('''
            QWidget#mainView {
                border-image: url(pic/background2.png) 0 0 0 0 stretch stretch;
            }
        ''')
        self.view.setObjectName("mainView")

        # 添加中间层图片，修改图片路径指向pic文件夹
        self.bg_image = QLabel(self.view)
        self.bg_image.setPixmap(QPixmap("pic/zhongjian1.png"))
        self.bg_image.setScaledContents(True)  # 允许图片缩放
        self.bg_image.setStyleSheet('background: transparent;')
        self.bg_image.lower()  # 将图片置于底层，但在背景之上

        # 确保滚动区域和其他组件保持透明
        self.setStyleSheet('''
            QScrollArea {
                border: none;
                background: transparent;
            }
            QLabel {
                background: transparent;
                color: white;
            }
            QPushButton {
                border: none;
                background-color: transparent;
            }
        ''')

        self.initUI()

    def resizeEvent(self, event):
        """重写调整大小事件以确保图片始终填满界面"""
        super().resizeEvent(event)
        self.bg_image.setGeometry(0, 0, self.view.width(), self.view.height())

    def initUI(self):
        self.vBoxLayout.setAlignment(Qt.AlignCenter)
        self.vBoxLayout.setSpacing(60)

        # 减小顶部空白，将整体内容向上移动
        self.vBoxLayout.addSpacing(200)  # 从400减少到200

        # 创建输入框
        self.inputs = {}
        input_configs = {
            'rows': ('', '10'),
            'cols': ('', '10'),
            'obstacles': ('', '20'),
            'points': ('', '3')
        }

        for key, (label_text, default) in input_configs.items():
            # 创建水平布局来放置标签和输入框
            input_layout = QHBoxLayout()
            input_layout.setAlignment(Qt.AlignCenter)

            # 修改标签背景图片，指向pic文件夹中的对应图片
            if key == 'rows':
                label = QLabel()
                label.setFixedSize(200, 60)
                label.setStyleSheet('''
                    QLabel {
                        border-image: url(pic/juxing.png);
                        background-position: center;
                        background-repeat: no-repeat;
                    }
                ''')
            elif key == 'cols':
                label = QLabel()
                label.setFixedSize(200, 60)
                label.setStyleSheet('''
                    QLabel {
                        border-image: url(pic/juxing2.png);
                        background-position: center;
                        background-repeat: no-repeat;
                    }
                ''')
            elif key == 'obstacles':
                label = QLabel()
                label.setFixedSize(200, 60)
                label.setStyleSheet('''
                    QLabel {
                        border-image: url(pic/zhangaiwu.png);
                        background-position: center;
                        background-repeat: no-repeat;
                    }
                ''')
            elif key == 'points':
                label = QLabel()
                label.setFixedSize(200, 60)
                label.setStyleSheet('''
                    QLabel {
                        border-image: url(pic/lujingdian.png);
                        background-position: center;
                        background-repeat: no-repeat;
                    }
                ''')
            input_layout.addWidget(label)

            # 创建输入框并设置背景，图片路径指向pic文件夹
            self.inputs[key] = QLineEdit()
            self.inputs[key].setText(default)
            self.inputs[key].setAlignment(Qt.AlignCenter)
            self.inputs[key].setFixedWidth(300)
            self.inputs[key].setFixedHeight(40)
            self.inputs[key].setFont(QFont("Microsoft YaHei", 12))
            self.inputs[key].setStyleSheet('''
                QLineEdit {
                    border: none;
                    color: white;
                    background-image: url(pic/anniu.png);
                    background-position: center;
                    background-repeat: no-repeat;
                }
            ''')
            input_layout.addWidget(self.inputs[key])

            self.vBoxLayout.addLayout(input_layout)

        # 添加状态标签
        self.status_label = QLabel("准备就绪")
        self.status_label.setAlignment(Qt.AlignCenter)
        self.vBoxLayout.addWidget(self.status_label)

        # 增加状态标签和按钮之间的间距
        self.vBoxLayout.addSpacing(60)  # 增加到60

        # 创建按钮水平布局
        button_layout = QHBoxLayout()
        button_layout.setAlignment(Qt.AlignCenter)
        button_layout.setSpacing(40)  # 设置按钮间距

        # 创建并配置按钮
        self.buttons = []  # 存储所有按钮的引用
        button_configs = [
            ('', self.generate_data, 'pic/SC2.PNG'),
            ('', self.edit_matrix, 'pic/SC.PNG'),
            ('', self.edit_points, 'pic/SC3.PNG'),
            ('', self.show_3d_visualization, 'pic/SC3.PNG')
        ]

        for btn_text, btn_func, bg_img in button_configs:
            button = HoverMoveButton('')
            # 获取图片实际大小，图片路径指向pic文件夹
            pixmap = QPixmap(bg_img)
            button.setFixedSize(pixmap.size())  # 设置按钮大小与图片完全一致
            button.setStyleSheet(f'''
                PrimaryPushButton {{
                    border: none;
                    background-image: url({bg_img});
                    background-position: center;
                    background-repeat: no-repeat;
                    background-color: transparent;
                }}
                PrimaryPushButton:hover {{
                    background-color: transparent;
                }}
                PrimaryPushButton:pressed {{
                    background-color: transparent;
                }}
            ''')
            button.clicked.connect(btn_func)
            button_layout.addWidget(button)
            self.buttons.append(button)

        # 保存按钮引用
        self.generate_button = self.buttons[0]
        self.edit_matrix_button = self.buttons[1]
        self.edit_points_button = self.buttons[2]
        self.visualize_button = self.buttons[3]

        self.vBoxLayout.addLayout(button_layout)

        # 添加底部弹性空间
        self.vBoxLayout.addStretch()

    def edit_matrix(self):
        """打开障碍物编辑器"""
        try:
            dialog = MatrixEditorDialog(self)
            dialog.exec_()
        except Exception as e:
            InfoBar.error(
                title='错误',
                content=f'打开障碍物编辑器失败: {str(e)}',
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=4000,
                parent=self
            )

    def show_3d_visualization(self):
        """显示3D可视化窗口"""
        try:
            # 检查数据文件是否存在
            required_files = [
                'data/quadrant_1.txt',
                'data/quadrant_2.txt',
                'data/quadrant_3.txt',
                'data/quadrant_4.txt'
            ]

            if not all(os.path.exists(f) for f in required_files):
                raise FileNotFoundError("请先生成所有象限数据文件")

            # 延迟导入防止主界面加载变慢
            from interfaces.map_visualizer import MapVisualizerWindow

            self.visual_window = MapVisualizerWindow()
            self.visual_window.show()

        except Exception as e:
            InfoBar.error(
                title='错误',
                content=str(e),
                position=InfoBarPosition.TOP,
                parent=self
            )

    def edit_points(self):
        """打开路径点编辑器"""
        try:
            dialog = PointsEditorDialog(self)
            dialog.exec_()
        except Exception as e:
            InfoBar.error(
                title='错误',
                content=f'打开路径点编辑器失败: {str(e)}',
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=4000,
                parent=self
            )

    def generate_data(self):
        """生成数据"""
        try:
            self.generate_button.setEnabled(False)
            self.status_label.setText('正在生成数据...')

            # 获取输入值
            rows = int(self.inputs['rows'].text())
            cols = int(self.inputs['cols'].text())
            obstacles = int(self.inputs['obstacles'].text())
            num_points = int(self.inputs['points'].text())

            # 生成环境矩阵
            self.status_label.setText('生成环境矩阵...')
            MatrixModule.generate_matrix(rows, cols, obstacles)

            # 生成点对
            self.status_label.setText('生成路径点对...')
            PointsModule.generate_point_pairs(num_points)

            # 组合文件
            self.status_label.setText('组合数据文件...')
            CombinerModule.combine_files()

            self.status_label.setText('数据生成完成!')
            InfoBar.success(
                title='成功',
                content='所有数据已生成',
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=2000,
                parent=self
            )

        except ValueError:
            self.status_label.setText('生成失败: 输入错误')
            InfoBar.error(
                title='输入错误',
                content='请确保所有输入都是有效的数字',
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=4000,
                parent=self
            )
        except Exception as e:
            self.status_label.setText('生成失败!')
            InfoBar.error(
                title='错误',
                content=str(e),
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=4000,
                parent=self
            )
        finally:
            self.generate_button.setEnabled(True)